/**
* Copyright (C)，2018，深圳万物安全科技有限公司
* FileName: index
* Author:   admin
* Data:     2018/11/10 12:12
* Description:
*/

<template>
    <div>
        <el-table :data="tasks" :style="styleObj">

            <el-table-column type="index" width="80" :label="$t('common.index')"></el-table-column>

            <el-table-column :label="$t('maps.tasksPage.name')" prop="taskName">
            </el-table-column>

            <el-table-column :label="$t('maps.tasksPage.progress')" prop="progress" width="250">
                <template slot-scope="scope">
                    <el-progress :percentage="scope.row.progress"></el-progress>
                </template>
            </el-table-column>

            <el-table-column :label="$t('maps.tasksPage.size')" prop="size">
                <template slot-scope="scope">
                    {{ scope.row.dataSize + ' (' + scope.row.dataSizeUnit + ')' }}
                </template>
            </el-table-column>

            <!--<el-table-column :label="$t('maps.tasksPage.useTime')" prop="useTime">-->
            <!--</el-table-column>-->

            <!--<el-table-column :label="$t('maps.tasksPage.needUseTime')" prop="needUseTime">-->
            <!--</el-table-column>-->

            <el-table-column :label="$t('common.operation')">
                <template slot-scope="scope">
                    <el-button type="text"
                               @click="startTask(scope)"
                               v-if="scope.row.taskStatus == 'stop'">
                        {{$t('maps.tasksPage.start')}}
                    </el-button>
                    <el-button type="text"
                               @click="stopTask(scope)"
                               v-if="scope.row.taskStatus == 'start'">
                        {{$t('maps.tasksPage.stop')}}
                    </el-button>
                    <el-button type="text"
                               @click="delTask(scope)">
                        {{$t('maps.tasksPage.delete')}}
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

    </div>
</template>

<script>

    import {DBFind, DBRemove, DBUpdate} from '@/api/NEDB/nedbApi'
    import {ipcRenderer} from 'electron'

    export default {
        name: "index",

        data() {
            return {
                msg: '地图离线下载工具',

                styleObj: {
                    width: '100%',
                    height: 0,
                },

                tasks: [],

                loading: null
            }
        },

        created: function () {
        },

        beforeRouteUpdate (to, from, next) {
            // 因为点击当前页面触发beforeRouteUpdate方法会触发两次
            // 第一次为两个时间都不为空，第二次为from的t不为空
            //
            // 从其他页面切换过来，to的t为空，from的t不为空
            //
            // 只有当前页面点击的才能触发beforeRouteUpdate方法

            if(to.path == from.path && typeof(to.query.t)!='undefined' && typeof(from.query.t)!='undefined'){
                // 两个时间都不是空的时候，表示是当前页面点击进入的
                // 设置beforeRouteUpdate的状态为允许触发
                this.$store.dispatch('setBeforeRouteUpdateActive', true);
                return;
            }

            // 增加判断：第一次切换进入页面时，to的t不为空，form的t为空；且this.$store.getters.beforeRouteUpdateActive为false
            // 重新进入页面：只有to的t为空，且设置允许触发的，才能触发，触发后就设置为false
            if(to.path == from.path && (
                (typeof(to.query.t)=='undefined' && this.$store.getters.beforeRouteUpdateActive)
                || (typeof(to.query.t)!='undefined' && typeof(from.query.t)=='undefined' && !this.$store.getters.beforeRouteUpdateActive)
            )){
                this.$store.dispatch('setBeforeRouteUpdateActive', false);
                this.init();
            }
        },

        methods: {
            init() {
                DBFind('DOWNLOADTASKCONF_DB', {}, (data) => {
                    this.tasks = data;
                });

                this.loading.close();
            },

            resetSize() {
                let fullHeight = document.getElementById("loadPageDiv").offsetHeight;
                // let dialogHeaderTitleHeight = document.getElementById("dialogHeaderTitle").offsetHeight;
                this.styleObj.height = fullHeight  + 'px';
            },

            startTask(scope) {
                const task = scope.row;

                scope.row.taskStatus = 'start';

                let that = this;
                setTimeout(() => {
                    that.downloadTaskBegin(task);
                }, 2000);
            },
            stopTask(scope) {
                this.$alert('功能未开发！', '提示', {
                    confirmButtonText: '确定'
                });
                return;
                const task = scope.row;
                ipcRenderer.send('stopDownloadTask', task);
            },
            delTask(scope) {
                this.$confirm(this.$t('common.isRealDelete'),
                    this.$t('common.messageBox.tips'), {
                        confirmButtonText: this.$t('common.btn_ok'),
                        cancelButtonText:  this.$t('common.btn_cancel'),
                        type: 'warning'
                    }).then(() => {

                    let taskId = scope.row.taskId;
                    let params1 = {
                        taskId: taskId
                    };
                    DBRemove('DOWNLOADTASKCONF_DB', params1, false, (data) => {
                        let params2 = {
                            taskParentId: taskId
                        };
                        DBRemove('DOWNLOADTASKS_DB', params2, false, (data) => {
                            this.init();
                        });
                    });
                }).catch(() => {
                });
            },

            downloadTaskBegin(task) {
                // 1.读取原有的任务配置文件，由JSON，转数组
                let params = {
                    taskParentId: task.taskId
                };
                DBFind('DOWNLOADTASKS_DB', params, (data) => {
                    const taskDescs = data;
                    const taskDesc = taskDescs[0];
                    ipcRenderer.send('startDownloadTask', taskDesc, task);
                });
            },

            openFullScreen(str) {
                this.loading = this.$loading({
                    lock: true,
                    text: this.$t(str),
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
            },

            taskProgressChange(arg){
                try {
                    for(let i in this.tasks){
                        if(this.tasks[i].taskId == arg.taskId){
                            this.tasks[i].taskStatus = 'start';
                            this.tasks[i].progress = parseFloat(arg.progress);

                            DBUpdate('DOWNLOADTASKCONF_DB',
                                {taskId: arg.taskId},
                                {$set: {
                                    progress: parseFloat(arg.progress),
                                    // currentDownload: arg.currentDownload
                                }
                                },
                                {},
                                (data)=>{
                            });

                            if(parseFloat(arg.progress) >= 100){
                                this.tasks[i].taskStatus = 'stop';
                            }
                            break;
                        }
                    }
                } catch (e) {

                }
            }

        },

        mounted: function () {
            this.resetSize();
            this.openFullScreen('maps.tasksPage.loadTasks')
            this.init();

            let that = this;

            ipcRenderer.on('taskProgressChange', function (event, arg) {
                that.taskProgressChange(arg);
            });

            ipcRenderer.on('stopTask', function(event, taskDesc){
                console.log(taskDesc);
            });
        }

    }
</script>

<style scoped>
    >>> .el-progress-bar{
        padding-right: 80px;
    }

    >>> .el-progress__text{
        margin-left: -15px;
    }
</style>